package com.xiaode.util.welink;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.huawei.welink.api.accesstoken.AuthV2TicketsRequest;
import com.huawei.welink.api.accesstoken.AuthV2TicketsResponse;
import com.huawei.welink.api.contact.user.AuthV2UseridRequest;
import com.huawei.welink.api.contact.user.AuthV2UseridResponse;
import com.huawei.welink.api.contactnew.department.ContactV2DepartmentDetailRequest;
import com.huawei.welink.api.contactnew.department.ContactV2DepartmentDetailResponse;
import com.huawei.welink.api.contactnew.department.ContactV2DepartmentListRequest;
import com.huawei.welink.api.contactnew.department.ContactV2DepartmentListResponse;
import com.huawei.welink.api.contactnew.role.ContactV1RoleDetailRequest;
import com.huawei.welink.api.contactnew.role.ContactV1RoleDetailResponse;
import com.huawei.welink.api.contactnew.role.ContactV1RoleSimplelistRequest;
import com.huawei.welink.api.contactnew.role.ContactV1RoleSimplelistResponse;
import com.huawei.welink.api.contactnew.role.ContactV1RolegroupListRequest;
import com.huawei.welink.api.contactnew.role.ContactV1RolegroupListResponse;
import com.huawei.welink.api.contactnew.role.ContactV1RolegroupSimplelistRequest;
import com.huawei.welink.api.contactnew.role.ContactV1RolegroupSimplelistResponse;
import com.huawei.welink.api.contactnew.user.ContactV2UserDetailRequest;
import com.huawei.welink.api.contactnew.user.ContactV2UserDetailResponse;
import com.huawei.welink.api.message.MessagesV2CardCommonRequest;
import com.huawei.welink.api.message.MessagesV2CardCommonResponse;
import com.huawei.welink.common.DefaultWeLinkClient;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.Student;
import com.xiaode.common.model.UserAccount;
import com.xiaode.common.model.WlDepartment;
import com.xiaode.common.model.WlRole;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class WeLinkUtil {
	
	public final static String ClientId = "20221018100541271786036";
	public final static String ClientSecret = "ca6abd6e-e387-498d-80ff-0a4eccee1569";
	
	private final static String AccessTokenUrl = "https://open.welink.huaweicloud.com/api/auth/v2/tickets";
	private final static String getWLUserIdUrl = "https://open.welink.huaweicloud.com/api/auth/v2/userid";
	private final static String getWLUserInfoUrl = "https://open.welink.huaweicloud.com/api/contact/v2/user/detail";
	private final static String getRolegroupList = "https://open.welink.huaweicloud.com/api/contact/v1/rolegroup/simplelist";
	private final static String getRoleList = "https://open.welink.huaweicloud.com/api/contact/v1/rolegroup/list";
	private final static String getRoleInfo = "https://open.welink.huaweicloud.com/api/contact/v1/role/detail";
	private final static String getUserList = "https://open.welink.huaweicloud.com/api/contact/v1/role/simplelist";
	private final static String getDepartmentList = "https://open.welink.huaweicloud.com/api/contact/v2/department/list";
	private final static String getDepartment = "https://open.welink.huaweicloud.com/api/contact/v2/department/detail";
//	private final static String addDepartment = "https://open.welink.huaweicloud.com/api/contact/v1/department/create";
//	private final static String delDepartment = "https://open.welink.huaweicloud.com/api/contact/v1/department/delete";
//	private final static String dpDepartment = "https://open.welink.huaweicloud.com/api/contact/v1/department/update";
//	private final static String upUser = "https://open.welink.huaweicloud.com/api/contact/v1/user/update";
	private final static String messagesNotice = "https://open.welink.huaweicloud.com/api/messages/v2/card/common";//消息通知
	
	/**
	 * 获取access_token
	 */
	public static String getAccessToken() throws Exception {
		if(Redis.use().exists(Const.welink.WELINK_ACCESS_TOKEN_TIME)){
			return Redis.use().get(Const.welink.WELINK_ACCESS_TOKEN_TIME);
		}
		DefaultWeLinkClient client = new DefaultWeLinkClient(AccessTokenUrl);
		AuthV2TicketsRequest req = new AuthV2TicketsRequest();
		req.setClientId(ClientId);
		req.setClientSecret(ClientSecret);
		AuthV2TicketsResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		Redis.use().setex(Const.welink.WELINK_ACCESS_TOKEN_TIME, jo.getInt("expires_in")-300, jo.getStr("access_token"));
		return jo.getStr("access_token");
	}
	
	/**
	 * 获取userId
	 */
	public static String getWLUserId(String wlcode) throws Exception {
		
		DefaultWeLinkClient client = new DefaultWeLinkClient(getWLUserIdUrl);
		AuthV2UseridRequest req = new AuthV2UseridRequest();
		req.setAccessToken(getAccessToken());
		req.setCode(wlcode);
		AuthV2UseridResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo.getStr("userId");
	}
	
	/**
	 * 取用户信息
	 * "code": "0",
		  "message": "OK",
		  "userStatus": "3",  
		  "userId": "zhangshan2@welink",
		  "corpUserId": "111",
		  "userNameCn" : "张三",
		  "userNameEn": "zhangsan",
		  "sex": "F",
		  "mobileNumber": "+86-15115127336",
		  "phoneNumber": ["+86-15115127336", "+86-15115127311"],
		  "mainCorpDeptCode": "1000",
		  "mainDeptCode": "100",
		  "corpDeptCodes": ["1000", "1001", "1002", "1003"],
		  "deptCodes": ["100", "101", "102", "103"],
		  "orderInDepts": {"100": 1, "101": 2, "102": 3},
		  "orderInCorpDepts": {"1000": 1, "1001": 2, "1002": 3},
		  "userEmail": "zhangsan@huawei.com",
		  "avatar", "https://xxx/ssxxx?t=2020-04-29%2020:49:46",
		  "employeeId": "001",
		  "landlineNumber": "0755-88888888",
		  "businessAddress": "广东省深圳",
		  "baseLocation": "",
		  "position": "产品经理",
		  "corpSecretary": "lisi",
		  "secretary": "lisi",
		  "remark": "test",
		  "isActivated": 1,
		  "isAdmin":1,
		  "sipNum": "30293402",
		  "isHidePhoneNumber": 0,
		  "seniorMode": 0,
		  "roleIds":["10", "11", "12"],
		  "extAttr":{"名称1": "value", "名称2": "value", "名称3": "value"},
		  "creationTime": "2018-05-03 13:58:02",
		  "lastUpdatedTime": "2018-05-03 13:58:02"
	 */
	public static JSONObject getWLUserInfo(String wlUserId) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getWLUserInfoUrl);
		ContactV2UserDetailRequest req = new ContactV2UserDetailRequest();
		req.setAccessToken(getAccessToken());
		req.setUserId(wlUserId);
		ContactV2UserDetailResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo;
	}
	
	
//	public static Boolean updateWLUserInfo() throws Exception {
//		List<WlUser> wlus = WlUser.dao.findAll();
//		
//		for(WlUser wlu : wlus) {
//			UserOtherInfo uoi = new UserOtherInfo();
//			uoi.setWlUserId(wlu.getUserId());
//			uoi.setUpdateTime(LocalDateTime.now());
//			uoi.save();
//		}
//		return true;
//	}
	
	
	/**
	 * 获取角色组
	 */
	public static JSONArray getRolegroupList() throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getRolegroupList);
		ContactV1RolegroupSimplelistRequest req = new ContactV1RolegroupSimplelistRequest();
		req.setAccessToken(getAccessToken());
		ContactV1RolegroupSimplelistResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo.getJSONArray("data");
	}
	
	/**
	 * 获取角色组中的角色
	 */
	public static JSONArray getRoleList(String roleGroupId) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getRoleList);
		ContactV1RolegroupListRequest req = new ContactV1RolegroupListRequest();
		req.setAccessToken(getAccessToken());
		req.setRoleGroupId(roleGroupId);
		ContactV1RolegroupListResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo.getJSONArray("data");
	}
	
	/**
	 * 获取角色详情
	 */
	public static JSONObject getRoleDetail(String roleId) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getRoleInfo);
		ContactV1RoleDetailRequest req = new ContactV1RoleDetailRequest();
		req.setAccessToken(getAccessToken());
		req.setRoleId(roleId);
		ContactV1RoleDetailResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo.getJSONObject("data");
	}
	
	/**
	 * 获取角色下的所有用户
	 * 每页显示数量。默认为10(不能大于50)
	 */
	public static JSONObject getUserList(String roleId, Integer pageNo, Integer pageSize) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getUserList);
		ContactV1RoleSimplelistRequest req = new ContactV1RoleSimplelistRequest();
		req.setAccessToken(getAccessToken());
		req.setRoleId(roleId);
		req.setPageNo(pageNo);
		req.setPageSize(pageSize);
		ContactV1RoleSimplelistResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo;
	}
	
	/**
	 * 获取基座部门列表
	 * pageSize:最大100
	 */
	public static JSONArray getDepartmentList(String deptCode, Integer pageNo, Integer pageSize) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getDepartmentList);
		ContactV2DepartmentListRequest req = new ContactV2DepartmentListRequest();
		req.setAccessToken(getAccessToken());
		req.setDeptCode(deptCode);
		req.setPageNo(pageNo);
		req.setPageSize(pageSize);
		ContactV2DepartmentListResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo.getJSONArray("data");
	}
	
	/**
	 * 获取基座部门详情
	 */
	public static JSONObject getDepartment(String deptCode) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(getDepartment);
		ContactV2DepartmentDetailRequest req = new ContactV2DepartmentDetailRequest();
		req.setAccessToken(getAccessToken());
		req.setDeptCode(deptCode);
		ContactV2DepartmentDetailResponse rsp = client.execute(req);
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo;
	}
	
	
	/**
	 * 添加组织部分（如新生分班添加班级）
	 */
//	public static JSONObject addDepartment(String pDeptCode, String deptName) throws Exception {
//		DefaultWeLinkClient client = new DefaultWeLinkClient(addDepartment);
//		ContactV1DepartmentCreateRequest req = new ContactV1DepartmentCreateRequest();
//		req.setAccessToken(getAccessToken());
//		req.setParentCode(pDeptCode);
//		req.setDeptNameCn(deptName);
//		ContactV1DepartmentCreateResponse rsp = client.execute(req);
//		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
//		int retcode = jo.getInt("code");
//		if(retcode != 0) {
//			System.err.println(jo);
//			return null;
//		}
//		return jo;
//	}
	
	
	/**
	 * 删除组织
	 */
//	public static JSONObject delDepartment(String deptCode) throws Exception {
//		DefaultWeLinkClient client = new DefaultWeLinkClient(delDepartment);
//		ContactV1DepartmentDeleteRequest req = new ContactV1DepartmentDeleteRequest();
//		req.setAccessToken(getAccessToken());
//		req.setDeptCode(deptCode);
//		ContactV1DepartmentDeleteResponse rsp = client.execute(req);
//		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
//		int retcode = jo.getInt("code");
//		if(retcode != 0) {
//			System.err.println(jo);
//			return null;
//		}
//		return jo;
//	}
	
	
	/**
	 * 修改组织名称
	 */
//	public static JSONObject upDepartment(String deptCode, String deptName) throws Exception {
//		DefaultWeLinkClient client = new DefaultWeLinkClient(dpDepartment);
//		ContactV1DepartmentUpdateRequest req = new ContactV1DepartmentUpdateRequest();
//		req.setAccessToken(getAccessToken());
//		req.setDeptCode(deptCode);
//		req.setDeptNameCn(deptName);
//		ContactV1DepartmentUpdateResponse rsp = client.execute(req);
//		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
//		int retcode = jo.getInt("code");
//		if(retcode != 0) {
//			System.err.println(jo);
//			return null;
//		}
//		return jo;
//	}
	
	
	/**
	 * 修改用户属性（此处只是修改部门）
	 */
//	public static JSONObject upUserDept(String userId, List<String> reqDeptCodesList) throws Exception {
//		DefaultWeLinkClient client = new DefaultWeLinkClient(upUser);
//		ContactV1UserUpdateRequest req = new ContactV1UserUpdateRequest();
//		req.setAccessToken(getAccessToken());
//		req.setUserId(userId);
//		req.setDeptCodes(reqDeptCodesList);
//		ContactV1UserUpdateResponse rsp = client.execute(req);
//		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
//		int retcode = jo.getInt("code");
//		if(retcode != 0) {
//			System.err.println(jo);
//			return null;
//		}
//		return jo;
//	}
	
	/**
	 * 消息通知
	 */
	public static JSONObject messagesNotice(String deptCode) throws Exception {
		DefaultWeLinkClient client = new DefaultWeLinkClient(messagesNotice);
		MessagesV2CardCommonRequest req = new MessagesV2CardCommonRequest();
		req.setAccessToken(getAccessToken());
		req.setMsgOwner("测试");//消息发送方,如“考勤”,长度不超过18字节
		req.setMsgRange("0");//0:按用户推送;1:按部门发送;2:按角色发送;默认0:按用户推送
		
		List<String> reqToUserListList = new ArrayList<>();//接收消息的人员ID
		reqToUserListList.add("m0xjqpzay2r5@d150e406a62");
		req.setToUserList(reqToUserListList);
		
		List<String> reqDepartmentListList = new ArrayList<>();//接收消息的部门ID
		reqDepartmentListList.add("qwe");
		req.setDepartmentList(reqDepartmentListList);
		
		List<String> reqRoleListList = new ArrayList<>();//接收消息的角色ID
		reqRoleListList.add("123");
		req.setRoleList(reqRoleListList);
		
		
		req.setMsgTitle("测试消息");
		req.setMsgContent("测试内容");
		
		req.setUrlType("html");//当前只支持“html”
		req.setUrlPath("http://www.baidu.com");
		
		req.setIsForceTips(1);//是否强提醒。 强提醒时PC WeLink收到消息,屏幕右下角会有弹窗提示。0:否;1:是。为空时默认为0,不强提醒
		
		MessagesV2CardCommonResponse rsp = client.execute(req);
		System.out.println(rsp.getBody());
		JSONObject jo = JSONUtil.parseObj(rsp.getBody());
		int retcode = jo.getInt("code");
		if(retcode != 0) {
			System.err.println(jo);
			return null;
		}
		return jo;
	}
	
	//--------------------------------------------------------------------------------------------初始话------------------------------------------------------------------------
	
	/**
	 * 初始化所有用户的逻辑
	 * 先要初始化角色和班级部门
	 */
	public static Boolean initAllUser() throws Exception {
		
		long m = System.currentTimeMillis();
		List<String> dc = Db.query("SELECT dept_code FROM wl_department");
		List<WlRole> roleList = WlRole.dao.find("SELECT * FROM wl_role WHERE role_group_code = ? OR role_group_code = ? ", "POST", "R5610E76747164BFD97C7FBED6AF4F430");
		
		for(int j = 0; j < roleList.size(); j++) {
			String roleId = roleList.get(j).getRoleCode();//ojr.getStr("roleId");
			userdg(roleId, 1, 50, dc);
		}
		
		long m2 = System.currentTimeMillis();
		
		System.out.println(m2 - m);
		
		return true;
	}
	
	
	public static void userdg(String roleId , Integer pageNo, Integer pageSize, List<String> dc) throws Exception {
		JSONObject userObj = getUserList(roleId, pageNo, pageSize);
		if(BeanUtil.isNotEmpty(userObj)) {
			JSONArray userl = userObj.getJSONArray("data");
			for(int x = 0; x < userl.size(); x++) {
				JSONObject oju = (JSONObject) userl.get(x);
//				System.out.println(oju);
				JSONObject jsonuser = getWLUserInfo(oju.getStr("userId"));
				if(BeanUtil.isNotEmpty(jsonuser)) {
					if(roleId.equals("R46EDD2B80E7C46B193D956069F14E3D2")){//学生
						
						String userId = jsonuser.getStr("userId");
						UserAccount ua = UserAccount.dao.findFirst("SELECT * FROM user_account WHERE eduID = ?", userId);
//						List<String> dc = Db.query("SELECT dept_code FROM wl_department");
						if(BeanUtil.isNotEmpty(ua)) {
							Student s = Student.dao.findFirst("SELECT * FROM student WHERE accountId = ?", ua.getId());
//							if(StrUtil.isNotBlank(jsonuser.getStr("avatar"))) {
//								s.setAvatarUrl(jsonuser.getStr("avatar"));
//							}
							s.setStudentNo(jsonuser.getStr("employeeId"));
							s.setName(jsonuser.getStr("userNameCn"));
							s.setSex(StrUtil.equals(jsonuser.getStr("sex"), "F")?2:1);
							s.setMobile(jsonuser.getStr("mobileNumber"));
							String gradeStr = jsonuser.getJSONObject("extAttr").getStr("年级组").split(";")[0];
							if(StrUtil.equals(gradeStr, "高一年级")) {
								s.setGrade(5);
							}
							if(StrUtil.equals(gradeStr, "高二年级")) {
								s.setGrade(1);
							}
							if(StrUtil.equals(gradeStr, "高三年级")) {
								s.setGrade(2);
							}
							s.setUpdateTime(LocalDateTime.now());
							String number = jsonuser.getJSONObject("extAttr").getStr("学籍号-学生");
							if(StrUtil.isNotBlank(number)) {
								s.setNumber(number);
							}
							List<String> deptCodes = JSONUtil.toList(jsonuser.getStr("deptCodes"), String.class) ;
							Set<String> dept = CollUtil.intersectionDistinct(deptCodes, dc);
							if(!dept.isEmpty()) {
								String deptCode = dept.iterator().next();
								WlDepartment wd = WlDepartment.dao.findFirst("SELECT * FROM wl_department WHERE dept_code = ?", deptCode);
								s.setClasId(wd.getOrgClassId());
							}
							s.update();
						}else {
							String account = jsonuser.getJSONObject("extAttr").getStr("学籍号-学生");
							ua = new UserAccount();
							ua.setAccount(account);
							ua.setAddTime(LocalDateTime.now());
							ua.setUserType(2);
							ua.setIsBindingPedestal(true);
							ua.setEduID(userId);
							ua.save();
							ua.setPassword(SecureUtil.md5(SecureUtil.md5("111111") + ua.getId() + Const.salt));
							ua.update();
							
							Student s = new Student();
//							if(StrUtil.isNotBlank(jsonuser.getStr("avatar"))) {
//								s.setAvatarUrl(jsonuser.getStr("avatar"));
//							}
							s.setStudentNo(jsonuser.getStr("corpUserId"));
							s.setName(jsonuser.getStr("userNameCn"));
							s.setSex(StrUtil.equals(jsonuser.getStr("sex"), "F")?2:1);
							s.setMobile(jsonuser.getStr("mobileNumber"));
							String gradeStr = jsonuser.getJSONObject("extAttr").getStr("年级组").split(";")[0];
							if(StrUtil.equals(gradeStr, "高一年级")) {
								s.setGrade(5);
							}
							if(StrUtil.equals(gradeStr, "高二年级")) {
								s.setGrade(1);
							}
							if(StrUtil.equals(gradeStr, "高三年级")) {
								s.setGrade(2);
							}
							s.setUpdateTime(LocalDateTime.now());
							String number = jsonuser.getJSONObject("extAttr").getStr("学籍号-学生");
							s.setNumber(number);
							List<String> deptCodes = JSONUtil.toList(jsonuser.getStr("deptCodes"), String.class) ;
							Set<String> dept = CollUtil.intersectionDistinct(deptCodes, dc);
							if(!dept.isEmpty()) {
								String deptCode = dept.iterator().next();
								WlDepartment wd = WlDepartment.dao.findFirst("SELECT * FROM wl_department WHERE dept_code = ?", deptCode);
								s.setClasId(wd.getOrgClassId());
							}
							s.setAddTime(LocalDateTime.now());
							s.setAccountId(ua.getId());
							s.setUserType(2);
							s.save();
						}
					}else {//老师
						
						String userId = jsonuser.getStr("userId");
						UserAccount ua = UserAccount.dao.findFirst("SELECT * FROM user_account WHERE eduID = ?", userId);
						if(BeanUtil.isNotEmpty(ua)) {
							Admin a = Admin.dao.findFirst("SELECT * FROM admin WHERE accountId = ?", ua.getId());
							if(BeanUtil.isEmpty(a)) {
								String account = jsonuser.getStr("mobileNumber").split("-")[1];//手机号作为账号
								a = new Admin();
								a.setPhone(account);
								if(StrUtil.isNotBlank(jsonuser.getStr("userEmail"))) {
									a.setEmail(jsonuser.getStr("userEmail"));
								}
								a.setName(jsonuser.getStr("userNameCn"));
								a.setGender(StrUtil.equals(jsonuser.getStr("sex"), "F")?2:1);
								a.setPhone(jsonuser.getStr("mobileNumber"));
								a.setAddTime(LocalDateTime.now());
								a.setAccountId(ua.getId());
								a.setUserType(1);
								a.save();
							}else {
								if(StrUtil.isNotBlank(jsonuser.getStr("employeeId"))){
									a.setJobNum(jsonuser.getStr("employeeId"));
								}
								a.setName(jsonuser.getStr("userNameCn"));
								a.setGender(StrUtil.equals(jsonuser.getStr("sex"), "F")?2:1);
								a.setPhone(jsonuser.getStr("mobileNumber"));
								a.setUpdateTime(LocalDateTime.now());
								a.setEmail(jsonuser.getStr("userEmail"));
								a.setSubjects(jsonuser.getStr("position"));
								if(StrUtil.isNotBlank(jsonuser.getStr("userEmail"))) {
									a.setEmail(jsonuser.getStr("userEmail"));
								}
								a.update();
								Boolean b = jsonuser.getInt("isAdmin")==0?false:true;
								if(ua.getCanLoginAdmin() != b) {
									ua.setCanLoginAdmin(b);
									ua.update();
								}
							}
						}else {
							String account = jsonuser.getStr("mobileNumber").split("-")[1];//手机号作为账号
							ua = new UserAccount();
							ua.setAccount(account);
							ua.setAddTime(LocalDateTime.now());
							ua.setUserType(1);
							ua.setIsBindingPedestal(true);
							ua.setEduID(userId);
							ua.save();
							ua.setPassword(SecureUtil.md5(SecureUtil.md5("111111") + ua.getId() + Const.salt));
							ua.update();
							
							Admin a = new Admin();
							a.setPhone(account);
							if(StrUtil.isNotBlank(jsonuser.getStr("userEmail"))) {
								a.setEmail(jsonuser.getStr("userEmail"));
							}
							a.setName(jsonuser.getStr("userNameCn"));
							a.setGender(StrUtil.equals(jsonuser.getStr("sex"), "F")?2:1);
							a.setPhone(jsonuser.getStr("mobileNumber"));
							a.setAddTime(LocalDateTime.now());
							a.setAccountId(ua.getId());
							a.setUserType(1);
							a.save();
						}
						
					}
				}
			}
			if(userObj.getInt("hasMore") == 1) {
				userdg(roleId, pageNo +1, pageSize, dc);
			}
		}
		
	}
	
	
	
	
	/**
	 * 获取所有部门
	 */
//	public static Boolean initAllAepartment() throws Exception {
//		JSONArray jsonD = getDepartmentList("0", 1, 100);
//		List<WlDepartment> wll = new ArrayList<WlDepartment>();
//		for(int x = 0; x < jsonD.size(); x++) {
//			JSONObject oju = (JSONObject) jsonD.get(x);
//			WlDepartment wld = new WlDepartment();
//			wld.setDeptCode(oju.getStr("deptCode"));
//			wld.setDeptNameCn(oju.getStr("deptNameCn"));
//			wld.setHasChildDept(oju.getInt("hasChildDept"));
//			wld.setOrderNo(oju.getInt("orderNo"));
//			wld.setParentCode(oju.getStr("parentCode"));
//			wld.setUpdateTime(LocalDateTime.now());
//			wld.setVisibleRange(oju.getInt("visibleRange"));
//			wll.add(wld);
//			if(oju.getInt("hasChildDept") == 1) {
//				aepartmentdg(oju.getStr("deptCode"), wll);
//			}
//		}
//		Db.batchSave(wll, wll.size());
//		return true;
//	}
//	public static void aepartmentdg(String childDept, List<WlDepartment> wll) throws Exception{
//		JSONArray jsonD = getDepartmentList(childDept, 1, 100);
//		for(int x = 0; x < jsonD.size(); x++) {
//			JSONObject oju = (JSONObject) jsonD.get(x);
//			WlDepartment wld = new WlDepartment();
//			wld.setDeptCode(oju.getStr("deptCode"));
//			wld.setDeptNameCn(oju.getStr("deptNameCn"));
//			wld.setHasChildDept(oju.getInt("hasChildDept"));
//			wld.setOrderNo(oju.getInt("orderNo"));
//			wld.setParentCode(oju.getStr("parentCode"));
//			wld.setUpdateTime(LocalDateTime.now());
//			wld.setVisibleRange(oju.getInt("visibleRange"));
//			wll.add(wld);
//			if(oju.getInt("hasChildDept") == 1) {
//				aepartmentdg(oju.getStr("deptCode"), wll);
//			}
//		}
//	}
	
	/**
	 * 获取所有班级部门
	 */
//	public static Boolean getClassDep() throws Exception {
//		List<WlDepartment> wll = new ArrayList<WlDepartment>();
//		String[] deps = {"255107072830","255218551658","254982125140"};
//		for(String dep : deps){
//			int grade = 0;
//			if(dep.equals("255107072830")) {
//				grade = 1;
//			}
//			if(dep.equals("255218551658")) {
//				grade = 2;
//			}
//			if(dep.equals("254982125140")) {
//				grade = 3;
//			}
//			JSONArray jsonD = getDepartmentList(dep, 1, 100);
//			for(int x = 0; x < jsonD.size(); x++) {
//				JSONObject oju = (JSONObject) jsonD.get(x);
//				WlDepartment wld = new WlDepartment();
//				wld.setDeptCode(oju.getStr("deptCode"));
//				wld.setDeptNameCn(oju.getStr("deptNameCn"));
//				wld.setHasChildDept(oju.getInt("hasChildDept"));
//				wld.setOrderNo(oju.getInt("orderNo"));
//				wld.setParentCode(oju.getStr("parentCode"));
//				wld.setUpdateTime(LocalDateTime.now());
//				wld.setVisibleRange(oju.getInt("visibleRange"));
//				List<String> userCodes = JSONUtil.toList(oju.getStr("managerId"), String.class);
//				wld.setManagerCode(userCodes.get(0));
//				wld.setGrade(grade);
//				wll.add(wld);
//			}
//		}
//		Db.batchSave(wll, wll.size());
//		return true;
//	}
	
	
	
	
	/**
	 * 获取所有角色
	 * 判断老的用户组和新的用户组的交集，删除老的余集，添加新的余集
	 */
	@Before(Tx.class)
	public static Boolean initAllRole() throws Exception {
		
		List<WlRole> savelist = new ArrayList<WlRole>(); 
		//获取所有角色组
		JSONArray rolegroupList = getRolegroupList();
		if(BeanUtil.isEmpty(rolegroupList)) {
			return false;
		}
		List<String> oldRoleCodeList = Db.query("SELECT role_code FROM wl_role");
		List<String> newRoleCodeList = new ArrayList<String>();
		List<JSONObject> newRoleList = new ArrayList<JSONObject>();
		for(int i = 0; i < rolegroupList.size(); i++) {
			JSONObject oj = (JSONObject) rolegroupList.get(i);
			String roleGroupId = oj.getStr("roleGroupId");
			String roleGroupName = oj.getStr("roleGroupName");
			//获取角色组中的角色
			JSONArray roleList = getRoleList(roleGroupId);
			for(int j = 0; j < roleList.size(); j++) {
				JSONObject rolej = (JSONObject) roleList.get(j);
				newRoleCodeList.add(rolej.getStr("roleId"));
				rolej.set("roleGroupId", roleGroupId);
				rolej.set("roleGroupName", roleGroupName);
				newRoleList.add(rolej);
			}
		}
		Collection<String> l = CollUtil.intersection(oldRoleCodeList, newRoleCodeList);
		oldRoleCodeList.removeAll(l);
		newRoleCodeList.removeAll(l);
		//删除老的
		for(String oldRoleCode : oldRoleCodeList) {
			Db.delete("DELETE FROM wl_role WHERE role_code = ?", oldRoleCode);
		}
		//添加新的
		for(JSONObject newRole : newRoleList) {
			String newCode = newRole.getStr("roleId");
			if(newRoleCodeList.contains(newCode)) {
				WlRole r = new WlRole();
				r.setRoleCode(newRole.getStr("roleId"));
				r.setRoleName(newRole.getStr("roleName"));
				r.setUpdateTime(LocalDateTime.now());
				r.setRoleGroupCode(newRole.getStr("roleGroupId"));
				r.setRoleGroupName(newRole.getStr("roleGroupName"));
				savelist.add(r);
			}
		}
		Db.batchSave(savelist, savelist.size());
		
		return true;
	}
	
	
	
	
}
